package cn.itcast.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * 处理所有post方法提交的汉字乱码的问题
 */
@WebFilter("/*")
public class EncodeFilter implements Filter {
    public void destroy() {
    }

    //执行过滤的功能
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //转成子接口
        HttpServletRequest request = (HttpServletRequest) req;
        //如果是post请求，对汉字进行编码
        if ("POST".equals(request.getMethod())) {
            request.setCharacterEncoding("utf-8");
        }
        if("GET".equals(request.getMethod())){
            MyHttpRequestWrapper wrapper = new MyHttpRequestWrapper(request);
        }


        //放行
        chain.doFilter(req, resp);
    }

    class MyHttpRequestWrapper extends HttpServletRequestWrapper {

        public MyHttpRequestWrapper(HttpServletRequest request) {
            super(request);
            // TODO Auto-generated constructor stub
        }

        // 重写getParameter方法
        @Override
        public String getParameter(String name) {
            // name为每个表中的字段名，value就是对应的值
            String value = super.getParameter(name);
            // 获得提交表单的方法
            String method = super.getMethod();
            if ("GET".equals(method)) {
                if (value != null) {
                    try {
                        // 进行编码转换
                        value = new String(value.getBytes("iso-8859-1"), "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return value;
        }
    }


    public void init(FilterConfig config) throws ServletException {

    }

}